//
//  CZAddressManagerViewController.m
//  nsj_iOS
//
//  Created by apple on 2017/1/7.
//  Copyright © 2017年 GCZ. All rights reserved.
//

#import "CZAddressManagerViewController.h"
#import "CZAddAddressViewController.h"
#import "CZAddPlaceViewController.h"
#import "CZAddressCell.h"
static NSString *const address_cell = @"address_cell";

@interface CZAddressManagerViewController ()<UITableViewDataSource, UITableViewDelegate>
@property (nonatomic, strong) NSMutableArray *addressArray;
@property (nonatomic, strong) UITableView *addressTableView;

@property (nonatomic, strong) LGRefreshView *refreshView;
@property (nonatomic, assign) NSInteger currentPage;
@end

@implementation CZAddressManagerViewController

- (NSMutableArray *__nonnull)addressArray {
    if (!_addressArray) {
        _addressArray = [[NSMutableArray alloc] init];
    }
    return _addressArray;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"管理收货地址";
    _currentPage = 1;
    [self getAddressData];
    self.view.backgroundColor = mRGBColor(249, 249, 249);
    UIButton *addAddressBtn = [UIButton buttonWithType:(UIButtonTypeSystem)];
    [addAddressBtn addTarget:self action:@selector(addAddress) forControlEvents:(UIControlEventTouchUpInside)];
    [self.view addSubview:addAddressBtn];
    [addAddressBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.bottom.right.equalTo(self.view);
        make.height.equalTo(@40);
    }];
    addAddressBtn.backgroundColor = mRGBColor(57, 204, 184);
    [addAddressBtn setTitle:@"添加新地址" forState:(UIControlStateNormal)];
    addAddressBtn.tintColor = [UIColor whiteColor];
    addAddressBtn.titleLabel.font = [UIFont systemFontOfSize:16];
    UITableView *addressTableView = [[UITableView alloc] init];
    [self.view addSubview:addressTableView];
    [addressTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).offset(64);
        make.left.right.equalTo(self.view);
        make.bottom.equalTo(addAddressBtn.mas_top);
    }];
    addressTableView.backgroundColor = mRGBColor(249, 249, 249);
    addressTableView.delegate = self;
    addressTableView.rowHeight = 168;
//    addressTableView.estimatedRowHeight = 170;
    addressTableView.dataSource = self;
    addressTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, Main_Screen_Width, 20)];
    
    headerView.backgroundColor = mRGBColor(249, 249, 249);
    addressTableView.tableHeaderView = headerView;
    [addressTableView registerNib:[UINib nibWithNibName:@"CZAddressCell" bundle:nil] forCellReuseIdentifier:address_cell];
    _addressTableView = addressTableView;
    
    
    
    _refreshView = [LGRefreshView refreshViewWithScrollView:self.addressTableView
                                             refreshHandler:^(LGRefreshView *refreshView){
                                                 [self.addressTableView.mj_footer setState:(MJRefreshStateIdle)];
                                                 _currentPage = 1;
                                                 [self getAddressData];
                                             }];
    _refreshView.center = CGPointMake(Main_Screen_Width / 2, _refreshView.center.y);
    _refreshView.tintColor = ThemeColor;
    _refreshView.backgroundColor = [UIColor clearColor];
    
    self.addressTableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        _currentPage ++;
        [self getAddressData];
    }];
    self.addressTableView.mj_footer.hidden = YES;
    
    // Do any additional setup after loading the view.
}
- (void)getAddressData {
    NSString *urlString = [NSString stringWithFormat:@"%@/api/web/index.php/v1/user-address/list",APP_HOST];
    [SVProgressHUD show];
    [GCZAFNetWorking POST:urlString params:@{@"token" : [[NSUserDefaults standardUserDefaults] objectForKey:User_Token], @"page" : @(_currentPage)} success:^(NSDictionary *response) {
        [SVProgressHUD dismiss];
        if ([response[@"code"] isEqualToString:@"200"]) {
            NSArray *arr = response[@"result"];
            if (!arr || arr.count < 1) {
                [self.addressTableView.mj_footer endRefreshingWithNoMoreData];
                return ;
            }
            if (_currentPage == 1) {
                self.addressArray = arr.mutableCopy;
            } else {
                for (NSDictionary *dic in arr) {
                    [self.addressArray addObject:dic];
                }
            }
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.addressTableView reloadData];
                self.addressTableView.mj_footer.hidden = NO;
            });
            [UIView animateWithDuration:0.2 animations:^{
                self.addressTableView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0);
            }];
            [_refreshView endRefreshing];
            [self.addressTableView.mj_footer endRefreshing];
        } else if ([response[@"code"] isEqualToString:@"300"]) {
            [UIView animateWithDuration:0.2 animations:^{
                self.addressTableView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0);
            }];
            [_refreshView endRefreshing];
            [self.addressTableView.mj_footer endRefreshingWithNoMoreData];
        } else {
            [UIView animateWithDuration:0.2 animations:^{
                self.addressTableView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0);
            }];
            [_refreshView endRefreshing];
            [self.addressTableView.mj_footer endRefreshing];
        }
    } failure:^(NSURLSessionDataTask *operation, NSError *error) {
        [UIView animateWithDuration:0.2 animations:^{
            self.addressTableView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0);
        }];
        [_refreshView endRefreshing];
        [self.addressTableView.mj_footer endRefreshing];
        [SVProgressHUD showErrorWithStatus:@"网络错误"];
    }];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.tabBarController.tabBar.hidden = YES;
    self.navigationController.navigationBar.alpha = 1;
    [(UIView*)[self.navigationController.navigationBar.subviews objectAtIndex:0] setAlpha:1.f];
    

    FBRetainCycleDetector *detector = [FBRetainCycleDetector new];
    [detector addCandidate:self];
    NSSet *retainCycles = [detector findRetainCycles];
    NSLog(@"%@", retainCycles);
}
- (void)addAddress {
    CZAddPlaceViewController *addAddressVC = [[CZAddPlaceViewController alloc] init];
    addAddressVC.addAddressCallBack = ^() {
        [self getAddressData];
    };
    [self.navigationController pushViewController:addAddressVC animated:YES];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (self.addressArray.count == 0) {
        self.addressTableView.mj_footer.hidden = YES;
    } else {
        self.addressTableView.mj_footer.hidden = NO;
    }
    return self.addressArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    CZAddressCell *cell = [tableView dequeueReusableCellWithIdentifier:address_cell];
    NSDictionary *dic = self.addressArray[indexPath.row];
    cell.userNameLabel.text = dic[@"user_name"];
    cell.phoneLabel.text = dic[@"mobile"];
    NSString *address = dic[@"address"];
    NSString *province = dic[@"province"];
    NSString *city = dic[@"city"];
    NSString *district = dic[@"district"];
    cell.addressLabel.text = [[[province stringByAppendingString:city] stringByAppendingString:district] stringByAppendingString:address];
    if ([dic[@"is_default"] isEqualToString:@"1"]) {
        cell.defaultBtn.selected = YES;
    } else {
        cell.defaultBtn.selected = NO;
    }
    [cell.defaultBtn addTarget:self action:@selector(defaultAddress:) forControlEvents:(UIControlEventTouchUpInside)];
    [cell.deleteBtn addTarget:self action:@selector(deleteaddress:) forControlEvents:(UIControlEventTouchUpInside)];
    [cell.editBtn addTarget:self action:@selector(editAddress:) forControlEvents:(UIControlEventTouchUpInside)];
    return cell;
}

- (void)deleteaddress:(UIButton *)button {
    CZAddressCell *cell = (CZAddressCell *)button.superview.superview;
    NSInteger index = [self.addressTableView indexPathForCell:cell].row;
    NSDictionary *dic = self.addressArray[index];
    NSString *urlString = [NSString stringWithFormat:@"%@/api/web/index.php/v1/user-address/delete",APP_HOST];
    
    [SVProgressHUD  show];
    [GCZAFNetWorking POST:urlString params:@{@"token" : [[NSUserDefaults standardUserDefaults] objectForKey:User_Token], @"address_id" : dic[@"address_id"]} success:^(id response) {
        [SVProgressHUD showSuccessWithStatus:@"删除地址成功"];
        [self.addressArray removeObjectAtIndex:index];
        [self.addressTableView reloadData];
    } failure:^(NSURLSessionDataTask *operation, NSError *error) {
        
    }];
}

- (void)editAddress:(UIButton *)button {
    CZAddressCell *cell = (CZAddressCell *)button.superview.superview;
    NSInteger index = [self.addressTableView indexPathForCell:cell].row;
    CZAddPlaceViewController *editVC = [[CZAddPlaceViewController alloc] init];
    editVC.dataDic = self.addressArray[index];
    [self.navigationController pushViewController:editVC animated:YES];
}

- (void)defaultAddress:(UIButton *)button {
    if (button.selected) {
        [SVProgressHUD showErrorWithStatus:@"不能取消默认地址"];
        return;
    }
    NSString *urlString = [NSString stringWithFormat:@"%@/api/web/index.php/v1/user-address/set-default",APP_HOST];

    CZAddressCell *cell = (CZAddressCell *)button.superview.superview;
    NSInteger index = [self.addressTableView indexPathForCell:cell].row;
    NSDictionary *dic = self.addressArray[index];
    
    [SVProgressHUD  show];
    [GCZAFNetWorking POST:urlString params:@{@"token" : [[NSUserDefaults standardUserDefaults] objectForKey:User_Token], @"address_id" : dic[@"address_id"]} success:^(id response) {
        [SVProgressHUD showSuccessWithStatus:@"默认地址设置成功"];
        
        for (int i = 0; i <  self.addressArray.count; i ++) {
            if (i == index) {
                NSDictionary *dic = self.addressArray[i];
                NSMutableDictionary *mDic = [dic mutableCopy];
                [mDic setObject:@"1" forKey:@"is_default"];
                self.addressArray[i] = mDic;
            } else {
                NSDictionary *dic = self.addressArray[i];
                NSMutableDictionary *mDic = [dic mutableCopy];
                [mDic setObject:@"0" forKey:@"is_default"];
                self.addressArray[i] = mDic;
            }
        }
        [self.addressTableView reloadData];
    } failure:^(NSURLSessionDataTask *operation, NSError *error) {
        [SVProgressHUD showErrorWithStatus:@"网络错误"];
    }];

    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)dealloc {
    
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
